﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DynamicChart.Annotation;
using DynamicChart.Model;
using DynamicChart.Util;

namespace DynamicChart.Repository;

public class MethodActuatorModelRepository : IActuatorModelRepository
{
    private readonly string _filePath;
    private List<ActuatorModel> _cache;

    public MethodActuatorModelRepository(string filePath)
    {
        _filePath = filePath;
        _cache = LoadFromMethod();
    }

    private List<ActuatorModel> LoadFromMethod()
    {
        List<Type> types = ClassLoader.LoadClass<ActuatorMethodClass>(_filePath);
        List<ActuatorModel> actuators = new List<ActuatorModel>();

        foreach (var type in types)
        {
            var methods = type.GetMethods();

            foreach (var method in methods)
            {
                var attribute = method.GetCustomAttribute<ActuatorMethodDescription>();

                if (attribute != null)
                {
                    actuators.Add(new ActuatorModel
                    {
                        Id = new Random().Next(),
                        Name = attribute.Name,
                        MethodSignature = method.Name
                    });
                }
            }
        }

        return actuators;
    }

    public IEnumerable<ActuatorModel> GetAll() => _cache;

    public ActuatorModel GetById(int id) => _cache.FirstOrDefault(m => m.Id == id);

    public void Add(ActuatorModel model)
    {
        // 方法方式通常是只读的，这里可以抛异常或忽略
        throw new NotImplementedException("Method source is read-only.");
    }

    public void Update(ActuatorModel model)
    {
        var index = _cache.FindIndex(m => m.Id == model.Id);
        if (index >= 0) _cache[index] = model;
    }

    public void Delete(int id)
    {
        var model = GetById(id);
        if (model != null) _cache.Remove(model);
    }

    public string GetSeriesConfig(int id)
    {
        throw new NotImplementedException();
    }
}